package com.record.utils;


import org.apache.commons.math3.distribution.TDistribution;
import java.util.Arrays;

public class TTestCalculator {

    public static TTestResult independentTTest(double[] g1, double[] g2) {
        int n1 = g1.length, n2 = g2.length;
        if (n1 < 2 || n2 < 2) {
            throw new IllegalArgumentException("每组样本量至少为2");
        }

        double mean1 = Arrays.stream(g1).average().orElse(0.0);
        double mean2 = Arrays.stream(g2).average().orElse(0.0);

        double var1 = Arrays.stream(g1).map(v -> Math.pow(v - mean1, 2)).sum() / (n1 - 1);
        double var2 = Arrays.stream(g2).map(v -> Math.pow(v - mean2, 2)).sum() / (n2 - 1);

        // 合并方差
        double sp2 = ((n1 - 1) * var1 + (n2 - 1) * var2) / (n1 + n2 - 2);
        double se = Math.sqrt(sp2 * (1.0 / n1 + 1.0 / n2));

        double t = (mean1 - mean2) / se;
        int df = n1 + n2 - 2;

        // 双侧 p 值
        TDistribution tDist = new TDistribution(df);
        double pValue = 2 * (1 - tDist.cumulativeProbability(Math.abs(t)));

        return new TTestResult(t, pValue, df);
    }
}
